from fastapi import APIRouter, Depends, HTTPException, status, Query
from typing import List, Optional, Dict

from app.dependencies_json import get_current_user, get_task_service
from app.models.schemas import (
    APIResponse, TaskInfo, TaskCreateRequest, TaskUpdateRequest,
    TaskListParams, PaginatedResponse, TaskStatus
)
from app.services.json_task_service import JSONTaskService

router = APIRouter()

@router.post("/", response_model=APIResponse[TaskInfo])
def create_task(
    request: TaskCreateRequest,
    current_user: dict = Depends(get_current_user),
    task_service: JSONTaskService = Depends(get_task_service)
):
    """创建新任务"""
    try:
        # 创建任务
        task_info = task_service.create_task(config=request.config)

        # 如果需要立即执行，启动任务
        if request.execute_immediately:
            task_service.start_task(task_info.id)

        return APIResponse(
            message="任务创建成功",
            data=task_info
        )

    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"创建任务失败: {str(e)}"
        )

@router.get("/", response_model=APIResponse[PaginatedResponse])
async def list_tasks(
    page: int = Query(1, ge=1, description="页码"),
    size: int = Query(20, ge=1, le=100, description="每页数量"),
    status_filter: Optional[TaskStatus] = Query(None, alias="status", description="状态过滤"),
    search: Optional[str] = Query(None, description="关键词搜索"),
    current_user: User = Depends(get_current_user),
    db: AsyncSession = Depends(get_db_session),
    task_service: TaskService = Depends(get_task_service)
):
    """获取任务列表"""
    try:
        params = TaskListParams(
            page=page,
            size=size,
            status=status_filter,
            search=search
        )
        
        result = await task_service.list_tasks(
            params=params,
            user_id=current_user.id,
            db=db
        )
        
        return APIResponse(
            message="获取任务列表成功",
            data=result
        )
        
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"获取任务列表失败: {str(e)}"
        )

@router.get("/{task_id}", response_model=APIResponse[TaskInfo])
async def get_task(
    task_id: str,
    current_user: User = Depends(get_current_user),
    db: AsyncSession = Depends(get_db_session),
    task_service: TaskService = Depends(get_task_service)
):
    """获取任务详情"""
    task_info = await task_service.get_task(task_id, db)
    
    if not task_info:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="任务不存在"
        )
    
    # 检查权限
    if task_info.user_id != current_user.id:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="无权访问此任务"
        )
    
    return APIResponse(
        message="获取任务详情成功",
        data=task_info
    )

@router.put("/{task_id}", response_model=APIResponse[TaskInfo])
async def update_task(
    task_id: str,
    request: TaskUpdateRequest,
    current_user: User = Depends(get_current_user),
    db: AsyncSession = Depends(get_db_session),
    task_service: TaskService = Depends(get_task_service)
):
    """更新任务"""
    try:
        # 如果任务正在运行且需要重启，先停止任务
        if request.restart_if_running:
            await task_service.stop_task(task_id, current_user.id, db)
        
        task_info = await task_service.update_task(
            task_id=task_id,
            config=request.config,
            user_id=current_user.id,
            db=db
        )
        
        if not task_info:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="任务不存在"
            )
        
        # 如果需要重启，启动任务
        if request.restart_if_running:
            await task_service.start_task(task_id, current_user.id, db)
        
        return APIResponse(
            message="任务更新成功",
            data=task_info
        )
        
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"更新任务失败: {str(e)}"
        )

@router.delete("/{task_id}", response_model=APIResponse[bool])
async def delete_task(
    task_id: str,
    current_user: User = Depends(get_current_user),
    db: AsyncSession = Depends(get_db_session),
    task_service: TaskService = Depends(get_task_service)
):
    """删除任务"""
    try:
        success = await task_service.delete_task(
            task_id=task_id,
            user_id=current_user.id,
            db=db
        )
        
        if not success:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="任务不存在"
            )
        
        return APIResponse(
            message="任务删除成功",
            data=True
        )
        
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"删除任务失败: {str(e)}"
        )

@router.post("/{task_id}/start", response_model=APIResponse[bool])
async def start_task(
    task_id: str,
    current_user: User = Depends(get_current_user),
    db: AsyncSession = Depends(get_db_session),
    task_service: TaskService = Depends(get_task_service)
):
    """启动任务"""
    try:
        success = await task_service.start_task(
            task_id=task_id,
            user_id=current_user.id,
            db=db
        )
        
        if not success:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="任务启动失败"
            )
        
        return APIResponse(
            message="任务启动成功",
            data=True
        )
        
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"启动任务失败: {str(e)}"
        )

@router.post("/{task_id}/stop", response_model=APIResponse[bool])
async def stop_task(
    task_id: str,
    current_user: User = Depends(get_current_user),
    db: AsyncSession = Depends(get_db_session),
    task_service: TaskService = Depends(get_task_service)
):
    """停止任务"""
    try:
        success = await task_service.stop_task(
            task_id=task_id,
            user_id=current_user.id,
            db=db
        )
        
        return APIResponse(
            message="任务停止成功" if success else "任务停止失败",
            data=success
        )
        
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"停止任务失败: {str(e)}"
        )

@router.get("/{task_id}/status", response_model=APIResponse[dict])
async def get_task_status(
    task_id: str,
    current_user: User = Depends(get_current_user),
    db: AsyncSession = Depends(get_db_session),
    task_service: TaskService = Depends(get_task_service)
):
    """获取任务状态"""
    try:
        status_info = await task_service.get_task_status(task_id, current_user.id, db)
        
        if not status_info:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="任务不存在"
            )
        
        return APIResponse(
            message="获取任务状态成功",
            data=status_info
        )
        
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"获取任务状态失败: {str(e)}"
        )

# 批量操作
@router.post("/batch/start", response_model=APIResponse[Dict[str, bool]])
async def batch_start_tasks(
    task_ids: List[str],
    current_user: User = Depends(get_current_user),
    db: AsyncSession = Depends(get_db_session),
    task_service: TaskService = Depends(get_task_service)
):
    """批量启动任务"""
    results = {}
    
    for task_id in task_ids:
        try:
            success = await task_service.start_task(task_id, current_user.id, db)
            results[task_id] = success
        except Exception as e:
            results[task_id] = False
    
    return APIResponse(
        message="批量启动任务完成",
        data=results
    )

@router.delete("/batch", response_model=APIResponse[Dict[str, bool]])
async def batch_delete_tasks(
    task_ids: List[str],
    current_user: User = Depends(get_current_user),
    db: AsyncSession = Depends(get_db_session),
    task_service: TaskService = Depends(get_task_service)
):
    """批量删除任务"""
    results = {}
    
    for task_id in task_ids:
        try:
            success = await task_service.delete_task(task_id, current_user.id, db)
            results[task_id] = success
        except Exception as e:
            results[task_id] = False
    
    return APIResponse(
        message="批量删除任务完成",
        data=results
    )
